<template>
    <div class="subpage buy-order-detail-container">
        <div class="buy-detail-box">
            <div class="project-item-info">
                <div class="project-img">
            		<img :src="item.smallPic" alt="">
                </div>
                <ul class="project-item-detail">
                    <li>
                        <p class="project-name">{{item.productName}}({{item.farmName}})</p>
                    </li>
                    <li>
                        <span>养殖地：{{item.cattleAddress}}</span>
                        <span>牧场：{{item.farmName}}</span>
                    </li>
                    <li>
                        <span>重量：{{item.productWeight}}元/kg</span>
                        <span>单价：{{item.salesPrice}}{{item.productPriceUnit}}</span>
                    </li>
                    <li>
                        <p class="project-price">
                            <span>{{item.totalPrice}}</span>{{item.productPriceUnit}}
                        </p>
						<p>
						   交货期：<span class="color-primary">{{item.deliveryTime}}</span>个月
						</p>
                    </li>
                </ul>
            </div>

            <div class="buy-goods-box">
                <ul class="buy-goods-top">
                    <li>
                        <p>我要求购</p>
                        <p>{{item.totalNum}}头</p>
                    </li>
                    <li>
                        <p>总重量</p>
                        <p>1300kg</p>
                    </li>
                    <li>
                        <p>总金额</p>
                        <p class="color-primary">{{item.totalNum * item.totalPrice}}元</p>
                    </li>
                    <li>
                        <p>求购时间</p>
                        <p>{{item.wantTime}}</p>
                    </li>
                </ul>
            </div>

			<div class="erbiaoId">
				<span>耳标ID</span>
				<span class="erbiao-detail" @click="toEebiao">详情 <img src="@/assets/img/home_img28.png" alt=""></span>
			</div>
           <div class="order-address-info">
                <div class="order-info-detail-title">收货地址</div>
                <div class="delivery-address-box" @click="editAddress">
                    <div class="address-detail">
                        <img src="@/assets/img/delivery_location_icon.png" alt="">
                        <div class="address-detail-text">
                            <p><span>{{firstList.name}}</span>{{firstList.tel}}</p>
                            <p>{{firstList.province}}&nbsp; {{firstList.city}}&nbsp; {{firstList.county}} &nbsp;{{firstList.addressDetail}}</p>
                        </div>
                    </div>
                    <div class="delivery-status">
                        <p class="color-gray">修改地址</p>
                        <van-icon name="arrow" class="arrow-right" />
                    </div>
              </div>
            </div>
			
			<div class="zf-box">
				<div class="zf-wrap">
					<h2>支付方式</h2>
				</div>
				<div class="cell-zf">
					<div class="left">
						<!-- 余额支付 -->
						<div class="left-box">
							<img src="@/assets/img/home_img29.png" alt="" style="margin-top: 14px;">
							<span class="wechart">余额支付</span>
							<i class="ye-money">{{accountMoney}}元</i>
						</div>
						<span class="radio">
							<div class="chenboxaa" @click="isCheckedClick3" v-if="isChecked3">
								<van-icon name="checked" color="#31BC8D" size="22px" tag="i" style="margin-top: 16px;" />
							</div>
							<div class="chenboxaa" @click="isCheckedClick3" v-else>
								<van-icon name="circle" color="#999" size="22px" tag="i" style="margin-top: 16px;" />
							</div>
						</span>
					</div>
				</div>
				<div class="cell-zf">
					<div class="left">
						<!-- 微信支付 -->
						<div class="left-box">
							<img src="@/assets/img/wechart.png" alt="">
							<span class="wechart">微信支付</span>
							
						</div>
						<span class="radio">
							<div class="chenboxaa" @click="isCheckedClick2" v-if="isChecked2">
								<van-icon name="checked" color="#31BC8D" size="22px" />
							</div>
							<div class="chenboxaa" @click="isCheckedClick2" v-else>
								<van-icon name="circle" color="#999" size="22px" />
							</div>
						</span>
					</div>
				</div>
				<div class="cell-zf">
					<div class="left" style="justify-content: start;">
						<span class="radio">
							<!-- 阅读且同意 -->
							<div class="chenboxaa" @click="isCheckedClick" v-if="isChecked">
								<van-icon name="checked" color="#31BC8D" size="22px" />
							</div>
							<div class="chenboxaa" @click="isCheckedClick" v-else>
								<van-icon name="circle" color="#999" size="22px" />
							</div>
						</span>
						<span class="wechart" style="margin-left: 16px;">阅读且同意 <i style="color: #31BC8D;" @click="to">《友牧农场服务协议》</i></span>
					</div>	
				</div>
			</div>
        </div>
		
		<div class="footer">
			<p class="total"><span>共{{item.totalNum}}头</span><span class="totalMoney">总计：{{item.totalNum * item.totalPrice}}元</span></p>
			<van-button round class="u-btn-default bind-btn" @click="buyAction">确定购买</van-button>
		</div>
		
		
		<!--  交易密码框 -->
		<van-overlay
		  :show="YEpayoverlay"
		/>
		<!-- 数字键盘 -->
		<van-number-keyboard
		  :show="YEpayoverlay"
		  @input="onInput"
		  @delete="onDelete"
		  @blur="showKeyboard = false"
		/>
		<div class="YEpayoverlay" v-show="YEpayoverlay">
			<div class="pay-head">输入交易密码 <van-icon name="cross" color="#31BC8D" size="20" tag="i" @click="hideKeyborard" /></div>
			<div class="pass-box">
				<!-- 密码输入框 -->
				<van-password-input
					:value="over_payData.paypwd"
					:focused="showKeyboard"
					@focus="showKeyboard = true"
				/>
				
			</div>
			<div class="pass-footer">
				<van-button round class="u-btn-default bind-btn pass-btn" @click="keepPass">确认</van-button>
			</div>
			
		</div>
		
    </div>
</template>

<style lang="scss">
	.buy-order-detail-container {
		.van-password-input__security li{
			border-right: 1px solid #D0CFCF;
			
			&:first-child {
				border-left: 1px solid #D0CFCF;
			}
			&:last-child {
				border: red !important;
			}
		}
		.van-password-input__security::after{
			border: 1px solid #D0CFCF;
		}
		.van-number-keyboard{
			z-index: 9999999 !important;
		}
	}
</style>

<script>
	import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
	import Vue from 'vue';
	import Storage from "@/utils/storage";
	import { Overlay, PasswordInput, NumberKeyboard, Dialog } from 'vant';
	Vue.use(Overlay).use(PasswordInput).use(NumberKeyboard);
	
	export default {
		components:{
			[Dialog.Component.name]: Dialog.Component
		},
		data(){
			return {
				item: {},
				isChecked: false,  // 协议
				isChecked2: false,  // 微信支付
				isChecked3: false,  // 余额支付
				accountMoney: '',   // 钱包余额
				firstList: {},
				showKeyboard: true,
				YEpayoverlay: false,
				over_payData: {   // 余额支付
					supplyOrderDetailId: '',
					paypwd: '',  //
					addressId: ''
				},
				
			}
		},
		computed:{
			...mapState([
					'product',
					'user'
				])
		},
		created() {
			this.getTab2Data() //  //   待付款 详情 
			this.getUserData()  // 用户信息数据 拿钱包余额
			this.getAddressList() // 收货地址
			this.saveStatus() // 初始化函数
		},
		methods: {
			to(){
				this.$router.push({
				    name: 'supplyAgreement',
				    query: { id: -1 }
				})
			},
			// 交易密码确认
			keepPass(){
				if(Storage.get('checkedYE')){
					if(this.over_payData.paypwd.length == 0){
						this.$tool.toast('请输入密码')
						return
					} else if(this.over_payData.paypwd.length < 6){
						this.$tool.toast('请输入6位数密码')
						return
					}
					this.over_payData.paypwd = this.$md5(this.over_payData.paypwd);  // 加密密码 md5
					console.log(this.over_payData)
					// 调余额支付接口
					this.$api.post('/api/supply/over_pay', this.over_payData)
					.then((res)=>{
						if(res.code == 0){
							console.log(res)
							let items = {
								totalNum: this.item.totalNum,
								totalPrice: this.item.totalPrice
							}
							this.$router.replace({
								path: '/my/buyOrder/buyOrderPaySuccess/' + res.data,
								query: {
									item: JSON.stringify(items)
								}
							})
							return
						}else if(res.data.code == 20014){   //交易密码错误
							this.over_payData.paypwd = '';
							this.$tool.toast(res.data.message)
						}
					})
				}
					
			},
			// 隐藏余额支付框
			hideKeyborard(){
				this.over_payData.paypwd = '';
				this.YEpayoverlay = false;
			},
			onInput(key) {
			    this.over_payData.paypwd = (this.over_payData.paypwd + key).slice(0, 6);
			},
			onDelete() {
			    this.over_payData.paypwd = this.over_payData.paypwd.slice(0, this.over_payData.paypwd.length - 1);
			},
			// 修改地址
			editAddress(){
				this.$router.push({
					path: '/home/addresslist/1',
					query: { from: 'tab2detail', orderId: this.$route.params.id }
				})
			},
			// 确定购买
			buyAction(){
				if(Object.keys(this.firstList).length == 0) { //  判断对象是否为空
					this.$toast({
						message: '请先添加收货地址'
					})
					return 
				}
				if(!this.isChecked2 && !this.isChecked3){
					this.$toast({
						message: '请先选择支付方式'
					})
					return
				}
				if(!this.isChecked){
					this.$tool.toast('请先阅读且同意《友牧农场服务协议》')
					return 
				}
				// 余额不足提示
				if(Storage.get('checkedYE') && this.accountMoney < this.item.totalNum * this.item.totalPrice) {
					this.$tool.toast('账户余额不足请选择其它支付方式');
					return 
				}
				// 余额支付
				if(Storage.get('checkedYE')){
					// 在vuex拿 isPayPwd 通过user拿   判断是否有设置交易密码  isPayPwd 1 代表有密码
					
					if(this.user.userInfo.idCard == null || this.user.userInfo.idCard == '') {  // 判断是否有实名
						this.$tool.toast('请先实名认证')
						setTimeout(()=>{
							this.$router.push({
								path: '/my/personalInfo/certification'
							})
						},800)
						return
					}
					if(this.user.userInfo.isPayPwd !== 1){
						// 没有设置交易密码 跳设置交易密码页
						this.$tool.toast('请先设置交易密码')
						setTimeout(()=>{
							this.$router.push({
								path: '/my/accountSet/setTradePassword/99'
							})
						},800)
						return
					}
					this.YEpayoverlay = true;
					
				} else {
					console.log('微信支付')
					let postData = {
						supplyOrderDetailId: this.over_payData.supplyOrderDetailId,
						addressId: this.over_payData.addressId
					}
					this.$api.post('/api/supply/wx_pay', postData)
					.then((res)=>{
						let resData = JSON.parse(res.data);
						if(resData.package == 'prepay_id=null'){
							this.$toast('登录已过期，请重新登录');
							setTimeout(()=> {
								this.$store.commit("userLoginOut");
								this.$router.push('/login')
							}, 800);
							return
						} else {
							WeixinJSBridge.invoke('getBrandWCPayRequest', {
							        "appId": resData.appId,
							        "timeStamp": resData.timeStamp,
							        "nonceStr": resData.nonceStr,
							        "package": resData.package,
							        "signType": resData.signType,
							        "paySign": resData.paySign
							    },
							    function (res) {
									if(res.err_msg == "get_brand_wcpay_request:ok" ){
										window.location.href="http://cs.umubao.com/index.html";
									}
							    })
						}
					})
				}
				
			},
			//   待付款 详情
			getTab2Data(){
				this.$api.get('/api/supply/getSupplyOrder/' + this.$route.params.id)
				.then(({data})=>{
					console.log(data)
					this.item = data;
					this.over_payData.supplyOrderDetailId = data.supplyOrderId; // 余额支付id
				})
			},
			// 通过这个接口拿 钱包余额
			getUserData(){
				this.$api.get('/api/user/detail')
				.then(({data})=>{
					this.accountMoney = data.accountMoney;  // 钱包余额
				})
			},
			// 获取地址列表接口
			getAddressList(){
				this.$api.post('/api/user/getaddresslist')
				.then(({data})=>{
					console.log(data)
					if(data.length > 0){
						this.firstList = data[0];
						this.over_payData.addressId = data[0].id; // 地址id
					}
				})
			},
			// 余额支付
			isCheckedClick3(){
				this.isChecked3 = !this.isChecked3;
				this.isChecked2 = false
				Storage.set('checkedYE', this.isChecked3)   //  存储 状态  同上
				Storage.del('checkedZF', this.isChecked2)   //  存储 状态  同上
			},	
			// 微信支付
			isCheckedClick2(){
				this.isChecked2 = !this.isChecked2;
				this.isChecked3 = false;
				Storage.set('checkedZF', this.isChecked2)   //  存储 状态  同上
				Storage.del('checkedYE', this.isChecked)   //  存储 状态  同上
			},
			isCheckedClick(){
				this.isChecked = !this.isChecked;
				Storage.set('checkedXY', this.isChecked)   //  存储 状态  同上
			},
			// 初始化函数
			saveStatus(){
				// 在这里获取选中支付状态渲染
				if(Storage.get('checkedYE')){
					this.isChecked3 = JSON.parse(Storage.get('checkedYE'));
				}
				if(Storage.get('checkedZF')){
					this.isChecked2 = JSON.parse(Storage.get('checkedZF'));
				}
				if(Storage.get('checkedXY')){
					this.Storage = JSON.parse(Storage.get('checkedXY'));
				}
			},
			// 跳耳标详情
			toEebiao(){
				this.$router.push({
					path: '/my/buyOrder/erbiao/' + this.item.id
				})
			}
		}
	}
	</script>

<style lang="scss" scoped>
  @import '../tabdetailScss.scss';
  .buy-detail-box{
	  width: 100%;
	  height: calc(100% - 63px);
	  overflow-y: scroll;
	  -webkit-overflow-scrolling: touch;
  }
	.erbiaoId {
		width: 100%;
		height: 33px;
		line-height: 33px;
		padding: 0 16px;
		background: rgba(49, 188, 141, 0.7);
		display: flex;
		justify-content: space-between;
		margin-top: 10px;

		span {
			color: #fff;
		}

		.erbiao-detail {
			font-size: 12px;

			img {
				width: 16px;
				vertical-align: middle;
				margin-left: 4px;
			}
		}
	}
	.zf-box{
		background-color: #fff;
		text-align: left;
		
		.zf-wrap{
			padding: 0 16px;
			border-bottom: 1px solid #F2F2F2;
			h2{
				width: 100%;
				height: 48px;
				line-height: 48px;
				font-size: 16px;
				color: #344047;
			}
		}
		.cell-zf{
			width: 100%;
			height: 63px;
			background-color: #fff;
			padding: 0 16px;
			.left{
				height: 63px;
				display: flex;
				align-items: center;
				position:relative;
				justify-content: space-between;
				.left-box{
					img{
						width: 32px;
						vertical-align: middle;
					}
					.wechart{
						margin-left: 16px;
						color: #5D6164;
					}
					.ye-money {
						position: absolute;
						left: 48px;
						bottom: 0;
						color: #F58523;
					}
				}
			}
		}
	}

	.footer{
		width: 100%;
		height: 63px;
		padding: 0 16px;
		line-height: 63px;
		position: fixed;
		left: 0;
		bottom: 0;
		background-color: #fff;
		box-shadow:2px 2px 5px #c2c2c2;
		-webkit-box-shadow:2px 2px 5px #c2c2c2;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.total{
			color: #F58523;
			font-size: 16px;
			font-weight: 500;
			float: left;
			.totalMoney{
				margin-left: 15px;
			}
		}
		
	}
	.bind-btn {
		    width: 144px;
			height: 51px;
			background:linear-gradient(90deg,#31BC8D 0%,#A6E29B 100%);
			border-radius:26px;
			color: #fff;
			font-size: 16px;
			box-shadow: none;
		  }
	.YEpayoverlay{
		width: 328px;
		position: fixed;
		left: 50%;
		top: 30%;
		margin-left: -164px;
		margin-top: -110px;
		background-color: #fff;
		border-radius:8px;
		z-index: 99;
		overflow: hidden;
		padding: 0 16px;
		.pay-head{
			width: 100%;
			height: 48px;
			line-height: 48px;
			text-align: center;
			background-color: #F8F8F8;
			color: #5D6164;
			font-size: 16px;
			font-weight: 500;
			position: relative;
			i{
				position: absolute;
				right: 0;
				top: 14px;
			}
		}
		.pass-box{
			margin-top: 29px;
			padding-bottom: 29px;
		}
		.pass-footer{
			width: 100%;
			text-align: center;
			padding-top: 14px;
			border-top: 1px solid #E5E5E5;
			padding: 14px 16px 14px 16px;
			.pass-btn{
				width:138px;
				height:44px;
			}
		}
	}
</style>